import { Injectable, Logger } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { CronExpression, SchedulerRegistry } from '@nestjs/schedule'
import dayjs from 'dayjs'
import { env } from '~/global/env'
import * as fs from 'fs'
import * as path from 'path'
// import * as iconv from 'iconv-lite'
import { LessThan } from 'typeorm'

import { CronOnce } from '~/common/decorators/cron-once.decorator'
import { ConfigKeyPaths } from '~/config'
import { AccessTokenEntity } from '~/modules/auth/entities/access-token.entity'
import { WeatherService } from '~/modules/weather/weather.service'

@Injectable()
export class CronService {
	private logger: Logger = new Logger(CronService.name)

	constructor(
		private readonly configService: ConfigService<ConfigKeyPaths>,
		private schedulerRegistry: SchedulerRegistry,
		private readonly weatherService: WeatherService, // 假设你有一个天气服务
	) {

	}

	@CronOnce(CronExpression.EVERY_DAY_AT_MIDNIGHT)
	async deleteExpiredJWT() {
		this.logger.log('--> 开始扫表，清除过期的 token')

		const expiredTokens = await AccessTokenEntity.find({
			where: {
				expired_at: LessThan(new Date()),
			},
		})

		let deleteCount = 0
		await Promise.all(
			expiredTokens.map(async (token) => {
				const { value, created_at } = token

				await AccessTokenEntity.remove(token)

				this.logger.debug(
					`--> 删除过期的 token：${value}, 签发于 ${dayjs(created_at).format(
						'YYYY-MM-DD H:mm:ss',
					)}`,
				)

				deleteCount += 1
			}),
		)

		this.logger.log(`--> 删除了 ${deleteCount} 个过期的 token`)
	}

	// 每两个小时执行一次
	@CronOnce(CronExpression.EVERY_HOUR)
	async readWeatherFile() {
		const appConfig = this.configService.get('app', { infer: true })

		// 检查是否启用天气文件读取功能
		if (!appConfig.enableWeatherFileRead) {
			this.logger.log('--> 天气文件读取功能已禁用，跳过执行')
			return
		}

		await this.weatherService.readFile()
		this.logger.log('--> 天气预警文件读取完成')
	}
}
